import axios from 'axios'
import store from '../store'
import router from '../router'
import { Toast } from 'vant'

// 默认请求的基础地址
const request = axios.create({
  baseURL: 'http://112.74.99.5:3000/web/api',
  timeout: 5000
})


request.interceptors.request.use(function (config) {
  const token = JSON.parse(localStorage.getItem('token'))
  if (token) {
    config.headers.Authorization = token
  }
  return config
}, function (error) {
  return Promise.reject(error);
})


// 响应拦截器，直接输出数据信息，并且直接在拦截器中实现请求失败
request.interceptors.response.use(function (response) {
  return response.data;
}, function (error) {
  if (error.response.status == 401 || error.response.status == 402) {
    // 调用退出登录的方法
    store.dispatch('resetUser')
    if (router.currentRoute.path !== '/login') {
      Toast(error.response.data.message)
      router.push('/login')
    }
  }
  return new Promise(() => { })
})

export default request